package com.thymeleaf.demo.controller;


import com.thymeleaf.demo.model.User;
import com.thymeleaf.demo.myexception.MyExcption;
import com.thymeleaf.demo.service.impl.UserServiceImpl;
import com.thymeleaf.demo.util.result.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sunny
 * @since 2020-12-22
 */
@Controller
@RequestMapping("/mall/admin/user")
public class UserController {

    @Autowired
    UserServiceImpl userService;

    @GetMapping("list")
    public ModelAndView list(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user/list");
        // 获取全部用户
        List<Map> userList = userService.getUserList();
        // 添加到模版中
        modelAndView.addObject("userList", userList);

        return modelAndView;
    }

    @GetMapping("insertUser")
    public ModelAndView insertUser(){
        return new ModelAndView("user/add");
    }

    @PostMapping("insertUser")
    public ModelAndView doInsertUser(User user){
        try{
            if(userService.insertUser(user)){
                return new ModelAndView("common/success");
            }else{
                return new ModelAndView("common/error");
            }
        }catch (MyExcption e){
            return new ModelAndView("/common/error", "errorMsg", ResultEnum.getResultByCode(Integer.parseInt(e.getMessage())).getMsg());
        }catch (Exception e){
            return new ModelAndView("/common/error", "errorMsg", e.getMessage());
        }
    }
}
